from array import array
from datetime import datetime
from hashlib import sha256
from json import dumps
from typing import List

from flask import Blueprint, jsonify, Flask, current_app, make_response, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from flask_restx import Resource, Api, reqparse, inputs

from exts import db
from models import user_role
from models.article import Article
from models.role import Role
from models.user import User
from utils.type import arrayType
from utils.http import fail_api,success_api

user_bp = Blueprint("user",__name__,url_prefix="/user")
# @qa_bp.route("/")
# @jwt_required(optional=False)
# class ArticleResource(Resource):
#    def get(self):
#       id =get_jwt_identity()
#       return ""
@user_bp.route("/", methods=['GET'])
def lists():
    per_page = int(request.args.get("per_page") or 10)
    page = int(request.args.get("page") or 1)
    user_name = request.args.get("user_name")
    query = User.query
    if user_name:
        query = query.filter_by(user_name=user_name)
    count = query.count()
    data = query.limit(per_page).offset((page - 1) * per_page).all()
    list = []
    for item in data:
        list.append(item.to_dict())
    re = {"list":list,"total":count,"page":page,"per_page":per_page}
    return success_api('请求成功',re)
@user_bp.route("/<int:id>", methods=['DELETE'])
def delete(id):
    user = User.query.get(id)
    try:
        db.session.delete(user)
        db.session.commit()
        return {"message": "删除成功", "code": 1}
    except:
        return {"message": "删除失败", "code": 0}

@user_bp.route("/password/<int:id>", methods=['PATCH'])
def updatePassWord(id):
    user = User.query.get(id)
    req = request.get_json()
    if  not req['password']:
        return {"message": "密码不能为空", "code": 0}
    try:
        user.password =  sha256(req['password'].encode('utf-8')).hexdigest()
        db.session.commit()
        return {"message": "修改成功", "code": 1}
    except:
        return {"message": "修改失败", "code": 0}

@user_bp.route("/store", methods=['POST'])
def store():
    #req = request.get_json()
    parser = reqparse.RequestParser()
    # 2.利用解析器对象添加 需要验证的参数
    parser.add_argument('username', type=str, help='用户名验证错误！', required=True, trim=True)
    parser.add_argument('realname', type=str, help='真实姓名验证错误！',  required=True)
    parser.add_argument('password', type=str, help='密码验证错误！',default="123456")
    parser.add_argument('email', type=str, help='email验证错误！',required=True,default="")
    parser.add_argument('avatar', type=str, help='头像验证错误！',default="")
    parser.add_argument('remark', type=str, help='备注验证错误！',default="")
    parser.add_argument('role',type=arrayType,required=True, help='角色！',default="")
    parser.add_argument('status', type=str, choices=[0,1],default=1)
    parser.add_argument('phone',help='手机号验证错误！',required=True,type=inputs.regex(r'(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}'))
    # 3.利用解析器对象进行验证
    try:
        args = parser.parse_args()
    except Exception as e:
        message = e.data.get('errors')
        return {"message": "参数验证错误", "code": 0}
    user = User.query.filter(User.username==args['username']).first()
    if user:
        return fail_api("用户名已存在")
    try:
        args['password'] = sha256(args['password'].encode('utf-8')).hexdigest()
        user = User.to_model(**args)
        db.session.add(user)
        role_ids = [i for i in args.role]
        roles = Role.query.filter(Role.id.in_(role_ids)).all()
        for r in roles:
            user.role.append(r)
        #db.session.add(roles)
        db.session.commit()
        #user_role.user_id = usre.id
        return success_api(msg="创建成功")
    except Exception as e:
        return fail_api(msg="创建失败")
@user_bp.route("/update/<int:id>", methods=['PATCH'])
def updateUserInfo(id):
    req = request.get_json()
    parser = reqparse.RequestParser()
    # 2.利用解析器对象添加 需要验证的参数
    parser.add_argument('username', type=str, help='用户名验证错误！', required=True, trim=True)
    parser.add_argument('realname', type=str, help='真实姓名验证错误！',  required=True)
    parser.add_argument('email', type=str, help='email验证错误！',default="")
    parser.add_argument('avatar', type=str, help='头像验证错误！',default="")
    parser.add_argument('remark', type=str, help='备注验证错误！',default="")
    parser.add_argument('role',type=arrayType,required=True, help='角色！',default="")
    parser.add_argument('status', type=str, choices=[0,1],default=1)
    parser.add_argument('phone',help='手机号验证错误！',required=True,type=inputs.regex(r'(13\d|14[579]|15[^4\D]|17[^49\D]|18\d)\d{8}'))
    # 3.利用解析器对象进行验证
    try:
        args = parser.parse_args()
    except Exception as e:
        return {"message": e.data['errors'], "code": 0}
    try:
        roles = args.get('role')
        args.pop('role')
        user = User.query.filter_by(id=id).update(args)
        u = User.query.filter_by(id=id).first()

        #角色id
        role_ids = [i for i in roles]
        roles = Role.query.filter(Role.id.in_(role_ids)).all()
        u.role = roles
        db.session.commit()
        return {"message": "修改成功", "code": 1}
    except Exception as e:
        print(e)
        return {"message": "修改失败", "code": 0}
@user_bp.get("/<int:id>")
@jwt_required(optional=False)
def user_roles(id):
    user =  User.query.get(id)
    print(user.role)
    print(11)
    role =[]
    for role in user.role:
        print(role.to_dict())
    #print(article.user)
    return {"data": user.to_dict(), "code": 1}
